python 统计list中各个元素出现的次数 |
您所在的位置:网站首页 › python list重复元素计数 › python 统计list中各个元素出现的次数 |
python 统计list中各个元素出现的次数
利用Python字典统计利用Python的collection包下Counter的类统计利用Python的pandas包下的value_counts的类统计
利用字典dict来完成统计
举例: a = [1, 2, 3, 1, 1, 2] dict = {} for key in a: dict[key] = dict.get(key, 0) + 1 print dict输出结果: >>>{1: 3, 2: 2, 3: 1} 利用Python的collection包下Counter的类举例: from collections import Counter a = [1, 2, 3, 1, 1, 2] result = Counter(a) print result输出结果: >>>{1: 3, 2: 2, 3: 1} Python的pandas包下的value_counts方法举例: import pandas as pd a = [1, 2, 3, 1, 1, 2] result = pd.value_counts(a) print result输出结果: >>>1 3 2 2 3 1注:利用pandas下的value_counts(),不仅可以统计list中各个元素出现的个数,还可对矩阵中的元素进行进行统计。 举例: import pandas as pd a = pd.DataFrame([[1,2,3], [3,1,3], [1,2,1]]) result = a.apply(pd.value_counts) print result输出结果: 0 1 2 1 2.0 1.0 1.0 # 表示元素1在第一列出现2次,在第二列出现1次,在第三列出现1次 2 NaN 2.0 NaN # 表示元素2在第一列出现0次,在第二列出现2次,在第三列出现0次 3 1.0 NaN 2.0 # 表示元素3在第一列出现1次,在第二列出现0次,在第三列出现2次 |
今日新闻 |
推荐新闻 |
CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3 |